from pathlib import Path

from .buildAb import run_essebr, run_rsi


def determine_topology_type(num_ebrdecom: int, num_abrdecom: int) -> dict[str, str | dict]:
    """确定拓扑类型并处理相关数据"""
    if num_ebrdecom > 0 and num_abrdecom > 0:
        # 原子绝缘体
        return {
            "type": "AI",
            "conclusion": "It is an atomic insulator.",
        }

    elif num_ebrdecom > 0 and num_abrdecom == 0:
        # 非常规原子绝缘体
        return handle_unconventional_insulator()

    elif num_ebrdecom == 0:
        # 拓扑绝缘体
        return {
            "type": "TI",
            "conclusion": "It's topological, since there is no solution for eBR decomposition.",
            "additional_data": {
                "details": "Please further check the compatibility relations (CRs). If satisfying CRs, it is a topological insulator; otherwise, it is a topological semimetal."
            },
        }

    else:
        return {"type": "ERROR", "conclusion": "Something wrong with this calculation.", "additional_data": {}}


def handle_unconventional_insulator() -> dict[str, str | dict]:
    """处理非常规绝缘体情况"""
    # 运行work_ess.sh获取essential BR信息
    run_essebr(brdatafile="tqc.data")

    # 读取essebr文件
    essebr_path = Path("essebr")
    possible_essebr = []
    possible_essebr_ind = []

    if not essebr_path.exists():
        return {
            "type": "ERROR",
            "conclusion": "Something wrong with this calculation.",
            "additional_data": {"details": "Essential BR file not found."},
        }

    for line in essebr_path.read_text().splitlines():
        tmp = line.strip().split()
        if len(tmp) >= 3 and int(tmp[-1]) > 0:
            possible_essebr.append(tmp[2])
            possible_essebr_ind.append(tmp[1].replace("@", "a"))

    if len(possible_essebr) == 1:
        # OAI1: 单一essential BR
        return handle_single_essential_br(possible_essebr, possible_essebr_ind)
    else:
        # OAI2: 多个essential BR
        return handle_multiple_essential_br(possible_essebr)


def handle_single_essential_br(possible_essebr: list[str], possible_essebr_ind: list[str]) -> dict[str, str | dict]:
    """处理单一essential BR情况"""
    run_rsi(brdatafile="tqc.data")

    # 读取分解数据
    decompose_file = Path(f"decompose_tqc.data_{possible_essebr_ind[0]}")
    decompose_data = []

    if decompose_file.exists():
        decompose_data = [line.strip() for line in decompose_file.read_text().splitlines()]

    return {
        "type": "OAI1",
        "conclusion": "It is unconventional with charge mismatch.",
        "additional_data": {"essential_br": possible_essebr[0], "+aBRs": decompose_data},
    }


def handle_multiple_essential_br(possible_essebr: list[str]) -> dict[str, str | dict]:
    """处理多个essential BR情况"""
    if possible_essebr:
        return {
            "type": "OAI2",
            "conclusion": "It is unconventional with charge mismatch.",
            "additional_data": {"essential_brs": possible_essebr, "details": "Multiple essential BRs found"},
        }
    else:
        return {
            "type": "OAI2",
            "conclusion": "It is unconventional with charge mismatch.",
            "additional_data": {"details": "There are more than one essential BRs."},
        }
